package edu.csl.study.shardingsphere.health.service.impl;

import edu.csl.study.shardingsphere.health.entity.User;
import edu.csl.study.shardingsphere.health.mapper.UserMapper;
import edu.csl.study.shardingsphere.health.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 自动生成代码
 * @since 2022-05-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


   String[] array= {"A","B","C","D","E","F","G"
           ,"H","I","J","K","L","M","N"
           ,"O","P","Q","R","S","T"
           ,"U","V","W","S","Y","Z"};

    @Override
    @Transactional(rollbackFor = Exception.class ) //必须这样，因为默认只回滚RuntimeException
    @ShardingTransactionType(TransactionType.BASE) //指定为XA模式
    public void processUsers() throws SQLException {

        insertUsers();
    }

    private List<Long> insertUsers() throws SQLException {
        List<Long> result = new ArrayList<>(10);
        Long index = 0l;
        for (Long i = 1L; i <= 10; i++) {
            User user = new User();
            user.setUserId(i);
            user.setUserName("user_" + random(i));
            baseMapper.insert(user);
            result.add(user.getUserId());

            System.out.println("Insert User:" + user.getUserId());
            index++;
        }
       if(index>1){
            throw  new SQLException(" 模拟错误！！！！");
        }
        return result;
    }
     private String random(Long index){
         Random r1 = new Random();
         int a1 = r1.nextInt(1000);
         Random r2 = new Random();
         int a2 = r2.nextInt(25);
         Random r3= new Random(3);
         int a3 = r2.nextInt(25);
         return array[a2]+ array[a3]+a1+ UUID.randomUUID();
     }
    @Override
    public List<User> getUsers() throws SQLException {
        return baseMapper.selectList(null);
    }

    @Override
    public void deleteAll() {
        baseMapper.delete(null);
    }

}
